package com.centaline.androidsalesblog.adapter;

import android.content.Context;
import android.net.Uri;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.BitmapTypeRequest;
import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.adapter.viewholder.LeftImgChatVH;
import com.centaline.androidsalesblog.adapter.viewholder.LeftTextChatVH;
import com.centaline.androidsalesblog.adapter.viewholder.RightImgChatVH;
import com.centaline.androidsalesblog.adapter.viewholder.RightTextChatVH;
import com.centaline.androidsalesblog.model.businissobject.RongUserInfoBo;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centanet.framework.utils.MyUrlLinkify;
import com.centanet.framework.utils.WebClickableSpan;

import java.util.ArrayList;

import io.rong.imlib.model.Message;
import io.rong.message.ImageMessage;
import io.rong.message.TextMessage;

/**
 * 聊天列表
 * Created by guilin on 16/3/16.
 */
public class ChatAdapter extends RecyclerView.Adapter {

    private final int ViewType1 = 1;//左侧文本
    private final int ViewType2 = 2;//右侧文本
    private final int ViewType3 = 3;//左侧图片
    private final int ViewType4 = 4;//右侧图片

    private final Context context;
    private final LayoutInflater layoutInflater;
    private final BitmapTypeRequest<String> mBitmapTypeRequest;
    private final DrawableRequestBuilder<Uri> uriRequestBuilder;
    private final ArrayList<Message> messageArrayList;
    private final ChatItemClick chatItemClick;
    private final WebClickableSpan.SpanOnClick spanOnClick;
    private RongUserInfoBo currentUserInfo, targetUserInfo;

    public ChatAdapter(Context context, BitmapTypeRequest<String> mBitmapTypeRequest,
                       DrawableRequestBuilder<Uri> uriRequestBuilder,
                       ArrayList<Message> messageArrayList,
                       ChatItemClick chatItemClick,
                       WebClickableSpan.SpanOnClick spanOnClick) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
        this.mBitmapTypeRequest = mBitmapTypeRequest;
        this.uriRequestBuilder = uriRequestBuilder;
        this.messageArrayList = messageArrayList;
        this.chatItemClick = chatItemClick;
        this.spanOnClick = spanOnClick;
    }

    public void setCurrentUserInfo(RongUserInfoBo currentUserInfo) {
        this.currentUserInfo = currentUserInfo;
        notifyDataSetChanged();
    }

    public void setTargetUserInfo(RongUserInfoBo targetUserInfo) {
        this.targetUserInfo = targetUserInfo;
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        Message message = messageArrayList.get(position);
        if (message.getMessageDirection() == Message.MessageDirection.RECEIVE) {//接收
            if (message.getContent() instanceof ImageMessage) {
                return 3;
            } else {
                return 1;
            }
        } else {//发送
            if (message.getContent() instanceof ImageMessage) {
                return 4;
            } else {
                return 2;
            }
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case ViewType1:
                return new LeftTextChatVH(inflaterByResId(R.layout.item_chat_text_left, parent));
            case ViewType2:
                return new RightTextChatVH(inflaterByResId(R.layout.item_chat_text_right, parent));
            case ViewType3:
                return new LeftImgChatVH(inflaterByResId(R.layout.item_chat_img_left, parent));
            case ViewType4:
                return new RightImgChatVH(inflaterByResId(R.layout.item_chat_img_right, parent));
            default:
                return null;
        }
    }

    protected View inflaterByResId(@LayoutRes int resId, ViewGroup parent) {
        return layoutInflater.inflate(resId, parent, false);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final Message message = messageArrayList.get(position);
        //时间显示规则判断
        boolean showTime;
        if (messageArrayList.size() == position + 1) {//当前显示为最顶部
            showTime = true;
        } else {
            long currentWhen;//当前消息时间
            long preWhen;//上一条消息时间
            if (message.getMessageDirection() == Message.MessageDirection.RECEIVE) {//接收
                currentWhen = message.getReceivedTime();
            } else {//发送
                currentWhen = message.getSentTime();
            }
            Message preMessage = messageArrayList.get(position + 1);
            if (preMessage.getMessageDirection() == Message.MessageDirection.RECEIVE) {//接收
                preWhen = preMessage.getReceivedTime();
            } else {//发送
                preWhen = preMessage.getSentTime();
            }
            showTime = currentWhen - preWhen > 5 * 60 * 1000;//是否超过5分钟
        }
        switch (getItemViewType(position)) {
            case ViewType1:
                LeftTextChatVH leftTextChatVH = (LeftTextChatVH) holder;
                long sentTime1 = message.getSentTime();
                leftTextChatVH.msgDate(DateUtil.timeRule(sentTime1), showTime);
                if (targetUserInfo != null) {
                    leftTextChatVH.userImg(mBitmapTypeRequest, targetUserInfo.getPortraitUrl());
                }
                if (message.getContent() instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message.getContent();
                    final String textContent = textMessage.getContent();
                    leftTextChatVH.msgContent(leftTextChatVH.atv_content, textContent);
                    leftTextChatVH.atv_content.setMovementMethod(LinkMovementMethod.getInstance());
                    MyUrlLinkify.addUrlLink(leftTextChatVH.atv_content, textContent, spanOnClick);
                    Linkify.addLinks(leftTextChatVH.atv_content, Linkify.PHONE_NUMBERS);
                    leftTextChatVH.ll_content.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            PopupMenu popupMenu = new PopupMenu(context, v);
                            popupMenu.getMenuInflater().inflate(R.menu.menu_chat_text, popupMenu.getMenu());
                            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    switch (item.getItemId()) {
                                        case R.id.action_copy:
                                            chatItemClick.copyText(textContent);
                                            break;
                                        case R.id.action_delete:
                                            chatItemClick.delete(message.getMessageId());
                                            break;
                                        default:
                                            break;
                                    }
                                    return true;
                                }
                            });
                            popupMenu.show();
                            return true;
                        }
                    });
                }
                break;
            case ViewType2:
                RightTextChatVH rightTextChatVH = (RightTextChatVH) holder;
                rightTextChatVH.sentStatus(message.getSentStatus());//发送状态
                long receivedTime1 = message.getReceivedTime();
                rightTextChatVH.msgDate(DateUtil.timeRule(receivedTime1), showTime);
                if (currentUserInfo != null) {
                    rightTextChatVH.userImg(mBitmapTypeRequest, currentUserInfo.getPortraitUrl());
                }
                if (message.getContent() instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message.getContent();
                    final String textContent = textMessage.getContent();
                    rightTextChatVH.msgContent(rightTextChatVH.atv_content, textContent);
                    rightTextChatVH.atv_content.setMovementMethod(LinkMovementMethod.getInstance());
                    MyUrlLinkify.addUrlLink(rightTextChatVH.atv_content, textContent, spanOnClick);
                    Linkify.addLinks(rightTextChatVH.atv_content, Linkify.PHONE_NUMBERS);
                    rightTextChatVH.ll_content.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            PopupMenu popupMenu = new PopupMenu(context, v);
                            popupMenu.getMenuInflater().inflate(R.menu.menu_chat_text, popupMenu.getMenu());
                            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    switch (item.getItemId()) {
                                        case R.id.action_copy:
                                            chatItemClick.copyText(textContent);
                                            break;
                                        case R.id.action_delete:
                                            chatItemClick.delete(message.getMessageId());
                                            break;
                                        default:
                                            break;
                                    }
                                    return true;
                                }
                            });
                            popupMenu.show();
                            return true;
                        }
                    });
                }
                break;
            case ViewType3:
                LeftImgChatVH leftImgChatVH = (LeftImgChatVH) holder;
                long sentTime2 = message.getSentTime();
                leftImgChatVH.msgDate(DateUtil.timeRule(sentTime2), showTime);
                if (targetUserInfo != null) {
                    leftImgChatVH.userImg(mBitmapTypeRequest, targetUserInfo.getPortraitUrl());
                }
                if (message.getContent() instanceof ImageMessage) {
                    ImageMessage imageMessage = (ImageMessage) message.getContent();
                    leftImgChatVH.msgImg(leftImgChatVH.img_msg,
                            uriRequestBuilder,
                            imageMessage.getRemoteUri(),
                            imageMessage.getThumUri());
                    leftImgChatVH.img_msg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    });
                    leftImgChatVH.img_msg.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            PopupMenu popupMenu = new PopupMenu(context, v);
                            popupMenu.getMenuInflater().inflate(R.menu.menu_chat_image, popupMenu.getMenu());
                            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    switch (item.getItemId()) {
                                        case R.id.action_delete:
                                            chatItemClick.delete(message.getMessageId());
                                            break;
                                        default:
                                            break;
                                    }
                                    return true;
                                }
                            });
                            popupMenu.show();
                            return true;
                        }
                    });
                }
                break;
            case ViewType4:
                RightImgChatVH rightImgChatVH = (RightImgChatVH) holder;
                rightImgChatVH.sentStatus(message.getSentStatus());
                long receivedTime2 = message.getReceivedTime();
                rightImgChatVH.msgDate(DateUtil.timeRule(receivedTime2), showTime);
                if (currentUserInfo != null) {
                    rightImgChatVH.userImg(mBitmapTypeRequest, currentUserInfo.getPortraitUrl());
                }
                if (message.getContent() instanceof ImageMessage) {
                    ImageMessage imageMessage = (ImageMessage) message.getContent();
                    Uri localUri = imageMessage.getLocalUri();
                    rightImgChatVH.msgImg(rightImgChatVH.img_msg,
                            uriRequestBuilder,
                            localUri == null ? imageMessage.getRemoteUri() : imageMessage.getLocalUri(),
                            imageMessage.getThumUri());
                    rightImgChatVH.img_msg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    });
                    rightImgChatVH.img_msg.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            PopupMenu popupMenu = new PopupMenu(context, v);
                            popupMenu.getMenuInflater().inflate(R.menu.menu_chat_image, popupMenu.getMenu());
                            popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    switch (item.getItemId()) {
                                        case R.id.action_delete:
                                            chatItemClick.delete(message.getMessageId());
                                            break;
                                        default:
                                            break;
                                    }
                                    return true;
                                }
                            });
                            popupMenu.show();
                            return true;
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    @Override
    public int getItemCount() {
        return messageArrayList.size();
    }

    /**
     * 聊天操作
     */
    public interface ChatItemClick {

        void delete(int messageId);

        void copyText(String text);

        void imgClick(String position);
    }
}
